package io.gitee.dtdage.app.boot.starter.pay.wx.service.impl;

import io.gitee.dtdage.app.boot.starter.pay.common.context.TradeBean;
import io.gitee.dtdage.app.boot.starter.pay.common.enums.Scene;
import io.gitee.dtdage.app.boot.starter.pay.wx.context.ConfigBean;
import io.gitee.dtdage.app.boot.starter.pay.wx.service.BaseTradeService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

/**
 * 微信H5交易接口实现类
 *
 * @author WFT
 * @since 2024/4/9
 */
@Service
@RequiredArgsConstructor
public class WxH5TradeServiceImpl extends BaseTradeService {

    @Override
    public Scene getId() {
        return Scene.wx_h5;
    }

    /**
     * @noinspection SpellCheckingInspection, Duplicates
     */
    @Override
    public <T extends TradeBean> Object payment(T param) throws Exception {
        ConfigBean configure = this.getConfigure(param.getClientId());
        //  场景信息
        JSONObject scene = new JSONObject()
                .put("payer_client_ip", param.getClientIp())
                .put("h5_info", new JSONObject().put("type", "Wap"));
        //  请求体
        JSONObject data = new JSONObject()
                //  公众号编号
                .put("appid", configure.getAppId())
                //  商户号
                .put("mchid", configure.getMchId())
                //  订单描述
                .put("description", param.getTradeTitle())
                //  订单编号
                .put("out_trade_no", String.valueOf(param.getId()))
                //  支付回调
                .put("notify_url", String.format(configure.getPayNotifyPath(), configure.getMchId(), param.getId()))
                //  订单金额
                .put("amount", new JSONObject().put("total", param.getTradePrice()).put("currency", "CNY"))
                //  场景信息
                .put("scene_info", scene)
                //  结算信息,不开启分账
                .put("settle_info", new JSONObject().put("profit_sharing", false));
        //  接口地址
        String api = "/v3/pay/transactions/h5";
        //  调用接口
        return this.execute(api, data.toString(), configure, HttpMethod.POST, response -> new JSONObject(response).getString("h5_url"));
    }

}
